package org.langqiao.thread;

import java.util.concurrent.locks.ReentrantLock;

public class Account {
	
	private ReentrantLock lock = new ReentrantLock();
	private String accountNo;
	private double balance;
	
	public Account(){
		
	}
	
	public Account(String accountNo,int balance){
		this.accountNo = accountNo;
		this.balance = balance;
	}
	
	
	public String getAccountNo() {
		return accountNo;
	}

	public void setAccountNo(String accountNo) {
		this.accountNo = accountNo;
	}

	public double getBalance() {
		return balance;
	}

	/*public void setBalance(double balance) {
		this.balance = balance;
	}*/

	public int hashCode(){
		return accountNo.hashCode();
	}
	
	//同步方法
	/*public synchronized void draw(double drawAmount){
		if(balance >= drawAmount){
			System.out.println(Thread.currentThread().getName() +",取钱成功，吐出钞票：" + drawAmount);
			try{
				Thread.sleep(1);
			}catch(Exception e){
				
			}
			balance = balance-drawAmount;
			System.out.println("取款后，所剩余额为："+balance);
		}else{
			System.out.println("你的余额不足,取款失败！");
		}
	}*/
	
	//同步锁
	public synchronized void draw(double drawAmount){
		lock.lock();
		try{
				
			if(balance >= drawAmount){
				System.out.println(Thread.currentThread().getName() +",取钱成功，吐出钞票：" + drawAmount);
				try{
					Thread.sleep(1);
				}catch(Exception e){
					
				}
				balance = balance-drawAmount;
				System.out.println("取款后，所剩余额为："+balance);
			}else{
				System.out.println("你的余额不足,取款失败！");
			}
		}catch(Exception e){
			
		}finally {
			lock.unlock();
		}
	}
	
	public boolean equals(Object obj){
		if(obj != null && obj.getClass() == Account.class){
			Account target = (Account)obj;
			return target.getAccountNo().equals(accountNo);
		}
		return false;
	}
}
